/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <ertps/xmlparser/XMLProfileManager.h>
#include <tinyxml2.h>
#include <xmlparser/XMLTreePart.h>
#include <xmlparser/XMLParserPart.h>
#include <xmlparser/XMLProfileManagerPart.h>

#include <transport/TransportDescriptorInterface.h>
#include <transport/SocketTransportDescriptor.h>

#include <xmlparser/attributes/XMLParticipantAttributes.h>

#ifdef _WIN32
#include <windows.h>
#endif  // ifdef _WIN32
#include <unistd.h>
#include <vector>
#include <cstdlib>
#include <elog/Log.hpp>

namespace evbs {
namespace ertps {
namespace xmlparser {

XMLP_ret XMLProfileManager::fillTransportAttributes(
    std::vector<std::shared_ptr<vbs::transport::TransportDescriptorInterface>>& transports,
    std::vector<std::string>& userTransports) {
    // 已解析的transport_id 保留在evbs中解析，participant中存储一个tranport_id string,需要单独处理赋值

    for (const auto& transportName : userTransports) {
        // 排除participant下transport_id被配置为走DSF共享队列模式:SHM_SAMPLE_DESCRIPTOR，但evbs未解析对应transport_descriptor而报错的情况
        if (transportName == xmlString::SHM_SAMPLE_DESCRIPTOR) {
            continue;
        }
        std::shared_ptr<vbs::transport::TransportDescriptorInterface> pDescriptor =
            XMLProfileManager::getTransportById(transportName);
        if (pDescriptor != nullptr) {
            transports.emplace_back(pDescriptor);
        } else {
            elogError(XMLPARSER, RetCode_t::RETCODE_NO_DATA, "Transport Node not found. Given ID: " << transportName);
            return XMLP_ret::XML_ERROR;
        }
    }
    return XMLP_ret::XML_OK;
}

XMLP_ret XMLProfileManager::fillParticipantAttributes(const std::string& profile_name, ParticipantAttributes& atts,
                                                      bool log_error) {
    vbsutil::xmlparser::up_participant_t participant_ptr(new vbsutil::xmlparser::ParticipantAttributes());
    if (vbsutil::xmlparser::XMLProfileManagerPart::getParticipantAttributes(profile_name, *participant_ptr.get(),
                                                                            log_error) != XMLP_ret::XML_OK) {
        elogError(XMLPARSER, RetCode_t::RETCODE_ERROR, "get Participant Attributes info failed");
        return XMLP_ret::XML_ERROR;
    }
    atts = *participant_ptr.get();
    if (XMLProfileManager::fillTransportAttributes(atts.rtps.userTransports,
                                                   participant_ptr.get()->rtps.userTransports) != XMLP_ret::XML_OK) {
        elogError(XMLPARSER, RetCode_t::RETCODE_ERROR, "Transport info fill failed");
        return XMLP_ret::XML_ERROR;
    }
#if 0
    /*
     * 自适应增删白名单中的环回口配置
     * vbs在transport type配置为ALL，存在SHM环境时，白名单自动过滤掉环回口，不存在SHM环境，自动添加换回口
     */
    if ((atts.rtps.transport_type == ertps::rtps::TransportTypeKind::TRANSPORT_TYPE_ALL)) {
        if ((access(vbsutil::constString::DSF_SHM_DRIVER_PATH, F_OK) != -1)) { // dsf driver is up
            for (auto& p_transport : atts.rtps.userTransports) {
                std::shared_ptr<vbs::transport::SocketTransportDescriptor> pDesc = std::dynamic_pointer_cast<vbs::transport::SocketTransportDescriptor>(p_transport);
                pDesc->interfaceWhiteList.erase(std::remove_if(pDesc->interfaceWhiteList.begin(), pDesc->interfaceWhiteList.end(),
                    [](const vbsutil::xmlparser::WhiteListAddr& item) { return (item.addr == "lo" || item.addr == "127.0.0.1"); }),
                    pDesc->interfaceWhiteList.end());
            }
            logWarning(XMLPARSER, "Transport info wipe off, remove 127.0.0.1/lo in interfaceWhiteList");
        } else {
            for (auto& p_transport : atts.rtps.userTransports) {
                std::shared_ptr<vbs::transport::SocketTransportDescriptor> pDesc = std::dynamic_pointer_cast<vbs::transport::SocketTransportDescriptor>(p_transport);
                auto it = std::find_if(pDesc->interfaceWhiteList.begin(), pDesc->interfaceWhiteList.end(),
                        [](const vbsutil::xmlparser::WhiteListAddr& item) { return (item.addr == "lo" || item.addr == "127.0.0.1"); });
                if (it == pDesc->interfaceWhiteList.end()) {
                    vbsutil::xmlparser::WhiteListAddr loAddr = {"127.0.0.1", 65535};
                    pDesc->interfaceWhiteList.push_back(loAddr);
                }
            }
            logWarning(XMLPARSER, "Transport info fill, add 127.0.0.1 to interfaceWhiteList");
        }
    }
#endif
    return XMLP_ret::XML_OK;
}

XMLP_ret XMLProfileManager::fillPublisherAttributes(const std::string& profile_name, PublisherAttributes& atts,
                                                    bool log_error) {
    return vbsutil::xmlparser::XMLProfileManagerPart::getPublisherAttributes(profile_name, atts, log_error);
}

XMLP_ret XMLProfileManager::fillSubscriberAttributes(const std::string& profile_name, SubscriberAttributes& atts,
                                                     bool log_error) {
    return vbsutil::xmlparser::XMLProfileManagerPart::getSubscriberAttributes(profile_name, atts, log_error);
}

XMLP_ret XMLProfileManager::fillTopicAttributes(const std::string& profile_name, TopicAttributes& atts) {
    return vbsutil::xmlparser::XMLProfileManagerPart::getTopicAttributes(profile_name, atts);
}

void XMLProfileManager::getDefaultParticipantAttributes(ParticipantAttributes& participant_attributes) {
    vbsutil::xmlparser::ParticipantAttributes xmlAttr =
        vbsutil::xmlparser::XMLProfileManagerPart::getDefaultParticipantAttributes();
    participant_attributes = xmlAttr;

    if (XMLProfileManager::fillTransportAttributes(participant_attributes.rtps.userTransports,
                                                   xmlAttr.rtps.userTransports) != XMLP_ret::XML_OK) {
        elogError(XMLPARSER, RetCode_t::RETCODE_ERROR, "Transport info fill failed");
    }
}

void XMLProfileManager::getDefaultPublisherAttributes(PublisherAttributes& publisher_attributes) {
    publisher_attributes = vbsutil::xmlparser::XMLProfileManagerPart::getDefaultPublisherAttributes();
}

void XMLProfileManager::getDefaultSubscriberAttributes(SubscriberAttributes& subscriber_attributes) {
    subscriber_attributes = vbsutil::xmlparser::XMLProfileManagerPart::getDefaultSubscriberAttributes();
}

void XMLProfileManager::getDefaultTopicAttributes(TopicAttributes& topic_attributes) {
    topic_attributes = vbsutil::xmlparser::XMLProfileManagerPart::getDefaultTopicAttributes();
}

}  // namespace xmlparser
}  // namespace ertps
}  // namespace evbs
